package com.itheima.chapter10.thread.demo12;

public class MyRunnable implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        // System.out.println("this:"+this);

        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {
                boolean result = synchronizedMethod(ticket);
                if (result) {
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
                synchronized (MyRunnable.class) {
                    if (ticket == 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(30);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "--->正在读第" + ticket + "页");
                        ticket--;
                    }
                }

            }
        }
    }

        private static synchronized boolean synchronizedMethod(int ticket) {
            if (ticket == 0) {
                return true;
            } else {
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "--->正在读第" + ticket + "页");
                ticket--;
                return false;
            }


       }
}
